package com.chx.rpc03;

import com.chx.api.UserService;
import com.chx.dto.User;

import java.io.*;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.net.Socket;

public class Stub {

    public static UserService getStub() throws IOException {
        InvocationHandler h = new InvocationHandler() {
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                Socket socket = new Socket("localhost", 8080);
                OutputStream os = socket.getOutputStream();
                DataOutputStream dos = new DataOutputStream(os);
                dos.writeInt((Integer) args[0]);
                dos.flush();
                InputStream is = socket.getInputStream();
                DataInputStream dis = new DataInputStream(is);
                return new User(dis.readInt(), dis.readUTF());
            }
        };
        Object o = Proxy.newProxyInstance(UserService.class.getClassLoader(), new Class[]{UserService.class}, h);
        return (UserService)o;
    }

}
